#!/usr/bin/python3

import glob

import json
import requests
import re
import os
import subprocess
import time
import shutil
import random

from bili.state import GlobalState
import utils
from typing import List, Dict, Tuple

'''
bilibili info get and gen
'''

from bili.constants import *


def make_dirs(dir):
    # dir=DIR_FOR_RESULT
    if os.path.exists(dir):
        if os.path.isdir(dir):
            return True
        else:
            return False
    try:
        os.makedirs(dir)
        return True
    except Exception as e:
        print("make dir err:",e)
        return False

def get_sub_id(result_dir,dir):
    subid=defaultSUBID
    try:
        with open(f"{dir}/group_sub_id.txt","r") as f:
            x=f.readlines()
            print("subid=",x)
            for line in x:
                line=line.strip(" \n")
                if len(line)>0:
                    subid=line
                    break
    except Exception as e:
        print(e)
        pass 
    
    targetDir=os.path.join(result_dir,subid)
    try:
        # videos others_store/bili  sub_id
        os.makedirs(targetDir)
    except:
        pass

    return subid


def start_jobs(globalState,basedir,dirs,result_dir):
    ################# start
    from bili.avbv import AVBV, Episodes, Bangumi

    # avid bvid: bvids.*.txt
    worker1=AVBV(globalState,result_dir)
    # episodes.bili , episodes.bili.* ,  *.episodes.bili
    worker2=Episodes(globalState,result_dir)
    # 剧集: bangumi.*.txt
    worker3=Bangumi(globalState,result_dir)

    def walk(d1,depth=0):
        if depth>10:
            return
        ds:List[str]=os.listdir(d1)
        for d2 in ds:
            print("d2=",d2)
            current=os.path.join(d1,d2)
            if not os.path.isdir(current):
                continue
            if not (d2.startswith("sub_") and d2.endswith(".bili.others")):
                print("?d2=",d2)
                continue

            d2=current
            subid=get_sub_id(result_dir,d2)
            print("d2=",d2)
            worker1.start(d2,subid)
            worker2.start(d2,subid)
            worker3.start(d2,subid)
            walk(d2,depth+1)

    for d1 in dirs:
        # 组, 第一层
        d1=os.path.join(basedir,d1)
        subid=get_sub_id(result_dir,d1)
        worker1.start(d1,subid)
        worker2.start(d1,subid)
        worker3.start(d1,subid)

        # 第二层~ ...
        walk(d1)



    ############# 同个aid组成的播放列表(同一个vod)
    # main_bv_av()
    ############# 合集: 由不同的aid组成的播放列表(同一个vod) , 这个视频信息 是由js手动弄的.
    # main_episodes()
    ############# 影视: season_id获取的播放列表(同一个vod)
    # main3_bangumi()





def log(*s):
    print(*s)


def initState(dirs)->GlobalState:
    globalState=GlobalState(dirs)
    return globalState

## main
def main():
    if len(os.sys.argv)<2:
        log("[E] need arg1 : ")
        log("        python3 {} xxxx/videos/".format(os.sys.argv[0]))
        exit(1)

    rootdir=os.sys.argv[1]
    if not os.path.exists(rootdir):
        log("[E] dir not exists : {}".format(rootdir))
        exit(2)

    rootdir=rootdir.rstrip("/")

    # video_dir="videos"
    rootdir,video_dir=os.path.split(rootdir)

    ###########dir
    cur=os.path.abspath((os.curdir))
    if rootdir!="":
        os.chdir(rootdir)

    result_dir=os.path.join(video_dir,DIR_FOR_RESULT)
    make_dirs(result_dir)
    abs_result_dir=os.path.abspath(result_dir)

    filter_pre=[]
    filter_suf=[".off"]
    groups=utils.getDirs(rootdir=video_dir,filter_pre=filter_pre,filter_suf=filter_suf)

    log("[INFO] start")
    log("[Debug] ", groups)
        
    
    g:str=""
    others=[]
    for g in groups:
        if not g.startswith("group_"):
            continue
        if not g.endswith(".others"):
            continue
        others.append(g)

    if len(others)==0:
        return
    
    globalState=initState(result_dir)    
    start_jobs(globalState,video_dir,others,result_dir)
    globalState.save()


    os.chdir(cur)


if __name__=="__main__":
    main()
    exit()

